package at.fhj.itm11.forum.data.impl;

import java.util.Date;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import at.fhj.itm11.forum.data.TestHelperDAO;
import at.fhj.itm11.forum.data.UserDAO;
import at.fhj.itm11.forum.model.Comment;
import at.fhj.itm11.forum.model.Icon;
import at.fhj.itm11.forum.model.Post;
import at.fhj.itm11.forum.model.Topic;
import at.fhj.itm11.forum.model.User;

@Named
@Stateless
public class TestHelperDAOImpl implements TestHelperDAO {

	@Inject
	private EntityManager em;

	@Inject
	@Named("userDAOImpl")
	private UserDAO userDAO;

	@Override
	public void cleanDB() {
		em.createNativeQuery("DELETE FROM Comment").executeUpdate();
		em.createNativeQuery("DELETE FROM Rating").executeUpdate();
		em.createNativeQuery("DELETE FROM Post").executeUpdate();
		em.createNativeQuery("DELETE FROM Topic").executeUpdate();
		em.createNativeQuery("UPDATE hibernate_sequence SET next_val = 1")
				.executeUpdate();
	}

	@Override
	public void createDemoData() {
		Topic demoTopic = createDemoTopic();
		Post demoPost = createDemoPost(demoTopic);
		createDemoComment(demoPost);
	}

	private void createDemoComment(Post demoPost) {
		Comment demoComment = new Comment();
		demoComment.setDate(new Date());
		demoComment.setPost(demoPost);
		demoComment.setText("Dies ist ein Demokommentar!");
		demoComment.setUser(demoPost.getUser());

		em.persist(demoComment);
	}

	private Post createDemoPost(Topic demoTopic) {
		Post post = new Post();
		post.setDate(new Date());
		post.setText("Dies ist ein Demobeitrag!");
		post.setTitle("DemoBeitrag");
		post.setTopic(demoTopic);
		post.setUser(demoTopic.getUser());

		em.persist(post);
		return post;
	}

	private Topic createDemoTopic() {
		Topic topic = new Topic();
		topic.setDate(new Date());
		topic.setDescription("Dies ist ein Demothema!");
		topic.setTitle("DemoThema");

		User user = userDAO.findByUsername("fhj");
		topic.setAuthor(user);

		Icon icon = em.find(Icon.class, 3L);
		topic.setIcon(icon);

		em.persist(topic);
		return topic;
	}

}
